#include "wifi.h"
#include "uart.h"
#include <string.h>
#include "utils.h"


#define BAUDRATE 4800

volatile uchar wifi_rx_buff[WIFI_BUFF_SIZE];
volatile uchar wifi_rx_count = 0;
volatile uchar wifi_rx_ok = 0;
volatile uchar wifi_rx_head = 0;

static void wifi_delay(void)
{
    uint i;
    for(i=0; i< 500; i++)
    {
        _nop_();
    }
}

void wifi_init(void)
{
    uart_init(BAUDRATE);
    uart_enable_recv();
    uart_enable_it();

    uart_send("AT+CIPMUX=1\r\n");
    wifi_delay();

    uart_send("AT+CIPSERVER=1,9090\r\n");
    wifi_delay();
}

void wifi_send(uchar * dat)
{
    uchar len = strlen(dat) + 2; // 2 is '\r\n'
    uchar len_str[3];

    uart_send("AT+CIPSEND=0,");
    num2char(len, len_str);
    // send length
    uart_send(len_str);
    uart_send("\r\n");`

    wifi_delay();
    // send msg
    uart_send(dat);
    uart_send("\r\n");
    wifi_delay();
}

#define HEAD '['
#define TAIL ']'
/* wifi receive interrupt routine service*/
void wifi_rx_it(void) interrupt 4
{
    if(RI)
    {

        REN = 0; // stop revice data
        if(!wifi_rx_ok) // recv full data?
        {
            if(wifi_rx_count == 0 && wifi_rx_head == 0)
            {
                if(SBUF == HEAD) // recv head
                    wifi_rx_head = 1; // set head mask
                RI = 0;
                REN = 1;
                return;
            }


            if(SBUF == TAIL) // recv tail
            {
                wifi_rx_ok = 1;
                wifi_rx_head = 0;
                wifi_rx_buff[wifi_rx_count] = '\0';
                RI = 0;
                REN = 1;
                return;
            }

            wifi_rx_buff[wifi_rx_count++] = SBUF;

            if(wifi_rx_count >= WIFI_BUFF_SIZE -1) // recv buff is full
            {
                wifi_rx_ok = 1;
                wifi_rx_head = 0;
                wifi_rx_buff[WIFI_BUFF_SIZE - 1] = '\0';
            }
            
        }
        REN = 1;
        RI = 0;
    }
}

